package cn.com.wxd.service.sms.webchinese;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;

import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpException;
import org.apache.commons.httpclient.NameValuePair;
import org.apache.commons.httpclient.methods.PostMethod;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import cn.com.wxd.common.CharUtil;
import cn.com.wxd.common.CharValidator;

/**
 * Title:中国建网短信发送服务
 * Description:cn.com.wxd.service.sms.webchinese
 * 
 * Company: wxd网站系统
 * Copyright: Copyright (c) 2015
 * All right reserved.
 * Created time: 2016-4-13 下午4:23:14
 *
 * @author WangXuDong
 * @version 1.0
 */
public class WebchineseSMS {
	private static final Logger log = LoggerFactory.getLogger(WebchineseSMS.class);
	private String uid;
	private String key;
	public WebchineseSMS(String uid,String key){
		this.uid = uid;
		this.key = key;
	}
	public int sentMessage(String phoneNum,String content){
		if(phoneNum==null||phoneNum.equals("")){
			return 0;
		}
		if(content==null||content.trim().equals("")){
			return 0;
		}
		HttpClient client = new HttpClient();
		PostMethod post = new PostMethod("http://utf8.sms.webchinese.cn"); 
		post.addRequestHeader("Content-Type","application/x-www-form-urlencoded;charset=utf-8");//在头文件中设置转码
		NameValuePair[] data ={ new NameValuePair("Uid", uid),new NameValuePair("Key", key),new NameValuePair("smsMob",phoneNum),new NameValuePair("smsText",content)};
		post.setRequestBody(data);

		try {
			client.executeMethod(post);
		} catch (HttpException e) {
			log.error("短信发送服务连接失败!"+e.getMessage(),e);
			post.releaseConnection();
			return 0;
		} catch (IOException e) {
			log.error(e.getMessage(),e);
			post.releaseConnection();
			return 0;
		}
		//Header[] headers = post.getResponseHeaders();
		//int statusCode = post.getStatusCode();
		String result = "";
		int resultInt;
		try {
			result = new String(post.getResponseBodyAsString().getBytes("utf-8"));
		} catch (UnsupportedEncodingException e) {
			log.error("短信发送结果获取!"+e.getMessage(),e);
			post.releaseConnection();
		} catch (IOException e) {
			log.error(e.getMessage(),e);
			post.releaseConnection();
		} 
		if(result==null||result.equals("")){
			log.error("短信发送连接超时!");
		}else{
			resultInt = CharUtil.stringParsInt(result);
			return resultInt;
		}
		post.releaseConnection();
		return 0;
	}
	public int sentMessages(String[] phoneNums,String content){
		if(phoneNums==null||phoneNums.length<=0){
			return 0;
		}
		if(content==null||content.trim().equals("")){
			return 0;
		}
		String phones = "";
		for (int i = 0; i < phoneNums.length; i++) {
			if(CharValidator.isMobile(phoneNums[i])){
				phones=phoneNums[i]+",";
			}
			if(i>=100){
				log.info("手机号码过多!只发送前100条短信！");
				break;
			}
		}
		phones.substring(0, phones.length()-1);
		HttpClient client = new HttpClient();
		PostMethod post = new PostMethod("http://utf8.sms.webchinese.cn"); 
		post.addRequestHeader("Content-Type","application/x-www-form-urlencoded;charset=utf-8");//在头文件中设置转码
		NameValuePair[] data ={ new NameValuePair("Uid", uid),new NameValuePair("Key", key),new NameValuePair("smsMob",phones),new NameValuePair("smsText",content)};
		post.setRequestBody(data);
		try {
			client.executeMethod(post);
		} catch (HttpException e) {
			log.error("短信发送服务连接失败!"+e.getMessage(),e);
			post.releaseConnection();
			return 0;
		} catch (IOException e) {
			log.error(e.getMessage(),e);
			post.releaseConnection();
			return 0;
		}
		//Header[] headers = post.getResponseHeaders();
		//int statusCode = post.getStatusCode();
		String result = "";
		int resultInt;
		try {
			result = new String(post.getResponseBodyAsString().getBytes("utf-8"));
		} catch (UnsupportedEncodingException e) {
			log.error("短信发送结果获取!"+e.getMessage(),e);
			post.releaseConnection();
		} catch (IOException e) {
			log.error(e.getMessage(),e);
			post.releaseConnection();
		} 
		if(result==null||result.equals("")){
			log.error("短信发送连接超时!");
		}else{
			resultInt = CharUtil.stringParsInt(result);
			return resultInt;
		}
		post.releaseConnection();
		return 0;
	}
	public int queryBatch(){
		//http://sms.webchinese.cn/web_api/SMS/?Action=SMS_Num&Uid=本站用户名&Key=接口安全秘钥
		try {
			String result="";
			URL url = new URL("http://sms.webchinese.cn/web_api/SMS/?Action=SMS_Num&Uid="+uid+"&Key="+key);
			URLConnection connection = url.openConnection();
            // 设置通用的请求属性
            connection.setRequestProperty("accept", "*/*");
            connection.setRequestProperty("connection", "Keep-Alive");
            connection.setRequestProperty("user-agent",
                    "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
            connection.setRequestProperty("Content-Type","application/x-www-form-urlencoded;charset=utf-8");
            // 建立实际的连接
            connection.connect();
            BufferedReader in = new BufferedReader(new InputStreamReader(
                    connection.getInputStream()));
            String line;
            while ((line = in.readLine()) != null) {
                result += line;
            }
            int resultInt = CharUtil.stringParsInt(result);
			return resultInt;
		} catch (MalformedURLException e) {
			if(log.isErrorEnabled()){
				log.error("短信发送服务连接失败!"+e.getMessage(),e);
			}
			return -1;
		} catch (IOException e) {
			log.error("短信发送结果获取!"+e.getMessage(),e);
		}
		return -1;
	}
}
